﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;

public class CrashLogger : MonoBehaviour 
{
    public static CrashLogger instance;
#if UNITY_ANDROID
    public static string sBundleID = "com.droidhen.idlechess";
#elif UNITY_IOS
    public static string sBundleID = "com.droidhen.idlechess.ios";
#else
    public static string sBundleID = "com.droidhen.idlechess";
#endif
    public static string sUserID = "-1";
    public static string sServerID = "-1";
    public static bool sInitSuccess = false;
    public static string sVersion = "";
    private static bool _sIsTest;
    public static bool sIsTest
    {
        get
        {
            return _sIsTest;
        }
        set
        {
            _sIsTest = value;
        }
    }
#if TEST
    private static string _server = "http://218.108.40.12/UpdateRes/zs/saverror2.php";
#else
    private static string _server = "http://game.idle-chess.com:20080/updatyen/zs/saverror2.php";
#endif

    private List<string> _errorCacheList = new List<string>();

    private Queue _loaderQueue = new Queue();

    private CrashLogPoster _currentPoster = null;

    void Awake()
    {
        Application.logMessageReceived += LogCallback;
        instance = this;
    }

    private void LogCallback(string condition, string stackTrace, LogType type)
    {
        if (type == LogType.Exception || type == LogType.Error)
        {
            string info = string.Format("{0}: {1}\n{2}",  type,condition, stackTrace);

            bool isSend = false;

            foreach (var st in _errorCacheList)
            {
                if (st.Equals(stackTrace))
                {
                    isSend = true;
                    break;
                }
            }

            if (isSend)
            {
                return;
            }

            _errorCacheList.Add(stackTrace);
            AddLog(info);
        }
    }

    public void AddLog(string log)
    {
        CrashLogPoster poster = new CrashLogPoster();
        poster.Init(_server, log);

        _loaderQueue.Enqueue(poster);
    }

    private bool _IsPosting()
    {
        return _currentPoster != null && !_currentPoster.isDone;
    }

    public void Update()
    {
        if (_IsPosting())
            return;

        if (_loaderQueue.Count > 0)
        {
            _currentPoster = _loaderQueue.Dequeue() as CrashLogPoster;
            StartCoroutine(_currentPoster.PostErrorLog());
        }
    }
}

public class CrashLogPoster
{

    public bool isDone = false;


    private string _server;
    private string _errorInfo;
    public void Init(string server, string errorInfo)
    {
        _server = server;
        _errorInfo = errorInfo;
    }

    public IEnumerator PostErrorLog()
    {
        Dictionary<string, string> headers = new Dictionary<string, string>();
        headers["Content-Type"] = "application/json; charset=utf-8";


        JsonData data = new JsonData();
        data["game"] = CrashLogger.sBundleID;
        data["version"] = CrashLogger.sVersion;
        data["error"] = _errorInfo;
        data["server"] = CrashLogger.sServerID;
        data["userid"] = CrashLogger.sUserID;

        string jsonStr = JsonMapper.ToJson(data);
        byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(jsonStr);

        WWW www = new WWW(_server, bytes, headers);

        yield return www;

        if (www.error != null)
        {
            Debug.Log("crash log post error:" + www.error);
        }
        else
        {
            Debug.Log("crash log post ok:" + www.text);
        }

        isDone = true;
    }
}